package com.lepu.app.fun.grow;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;

import com.app.application.MyApplication;
import com.app.config.UserConfig;
import com.app.utils.Const;
import com.app.utils.Setting;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.main.LogUtilBase;
import com.core.lib.utils.main.UIHelper;
import com.lepu.app.fun.grow.bean.PhotoItem;
import com.lepu.app.main.activity.MainTabActivity;
import com.lepu.app.usercenter.bean.LoginInfo;

/*
 * 申请热门相册
 */
public class GrowApplyPhotoManager implements AsyncRequest {

	private static final String REQUEST_UPLOAD_IMAGE = "request_upload_image";
	private static final String REQUEST_APPLY_HOT_PHOTO = "request_apply_hot_photo";

	private static final int MSG_APPLY_PHOTO_SUCCESS = 10;
	private static final int MSG_APPLY_PHOTO_FAIL = 11;
	private static final int MSG_UPLOAD_IMAGE_ERROR = 20;

	private ArrayList<PhotoItem> mDataList = null;
	private int mCurrentIndex = 0;

	private static GrowApplyPhotoManager mInstance = null;
	private LoginInfo mLoginInfo = MyApplication.getInstance().getLoginInfo();

	private boolean mIsApplyHotPhoto = false;

	public boolean mIsUploading = false;

	private int mCurrentItemId = 0;
	private String mCurrentDateString = "";

	public static GrowApplyPhotoManager getInstance() {
		if (mInstance == null) {
			mInstance = new GrowApplyPhotoManager();
		}

		return mInstance;
	}

	public void destroy() {
		mInstance = null;

		mIsUploading = false;
		LogUtilBase.LogD(null, "取消云端同步上传图片");
	}

	public void setIsApplyHotPhoto(boolean applyHotPhoto) {
		mIsApplyHotPhoto = applyHotPhoto;
	}

	public void init(String dateString) {

		mCurrentDateString = dateString;
		String uid = mLoginInfo.UserID;
		mDataList = PhotoItem.getPhotosByDateNoUpdate(uid, dateString);

		if (mDataList != null) {
			LogUtilBase
					.LogD(null, String.format("需要上传%d张图片", mDataList.size()));
		}else{
			mDataList = new ArrayList<PhotoItem>();
		}
	}

	public void uploadImageContent() {

		if (mInstance == null) {
			return;
		}

		mIsUploading = true;

		if (mCurrentIndex <= mDataList.size() - 1) {
			PhotoItem item = mDataList.get(mCurrentIndex);

			mCurrentItemId = item.id;

			Map<String, File> fileMap = new HashMap<String, File>();
			fileMap.put("Photo", new File(item.imagePath));

			Map<String, Object> map = new HashMap<String, Object>();
			JSONObject params = new JSONObject();
			try {
				params.put("DeviceID", Setting.DEVICEID);
				params.put("ApplicationID", Setting.APPLICATIONID);

				params.put("UserID", mLoginInfo.UserID);
				params.put("LoginToken", mLoginInfo.LoginToken);

				if (item.modifyState == PhotoItem.MODIFY_YES) {
					params.put("PhotoID", item.pictureId);// 修改
				}

				params.put("TakePictureDate", item.addTime);
				params.put("NativePhotoID", item.id);
				params.put("Description", item.desc);

				map.put("ht", params);

				String url = Setting.getAddPhotoUrl();
				if (item.modifyState == PhotoItem.MODIFY_YES) {
					url = Setting.getModifyPhotoUrl();// 修改
				}

				ApiClient.http_post(url, map, fileMap, this,
						REQUEST_UPLOAD_IMAGE, false);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		requestApplyHotPhotoNew();
	}

	private void requestApplyHotPhotoNew() {
		if (mInstance == null) {
			return;
		}

		// 申请热门相册
		if (mIsApplyHotPhoto) {
			// 说明上传完图片了，需要申请热门相册
			if (mCurrentIndex > mDataList.size() - 1) {

				String albumName = UserConfig.getConfigString(
						MainTabActivity.getInstance(),
						Const.CONFIG_APP_ALBUM_NAME,
						Const.DEFAULT_CUSTOM_ALBUM_NAME);
				String albumApplyDesc = UserConfig.getConfigString(
						MainTabActivity.getInstance(),
						Const.CONFIG_APP_ALBUM_APPLY_DESC, "");

				ArrayList<PhotoItem> dataList = PhotoItem.getPhotosByDate(
						mLoginInfo.UserID, mCurrentDateString);
				String result = "";
				if (dataList != null && dataList.size() > 0) {
					StringBuilder sb = new StringBuilder();
					for (int i = 0; i < dataList.size(); i++) {
						sb.append(dataList.get(i).pictureId);
						sb.append("|");
					}
					sb.deleteCharAt(sb.length() - 1);

					result = sb.toString();

					Map<String, Object> map = new HashMap<String, Object>();
					JSONObject params = new JSONObject();
					try {
						params.put("DeviceID", Setting.DEVICEID);
						params.put("ApplicationID", Setting.APPLICATIONID);

						params.put("UserID", mLoginInfo.UserID);
						params.put("LoginToken", mLoginInfo.LoginToken);

						params.put("AlbumDescription", albumApplyDesc);
						params.put("PhotoIDs", result);//
						params.put("AlbumName", albumName);
						params.put("AlbumDate", mCurrentDateString);// new add
					} catch (Exception e) {
						e.printStackTrace();
					}
					map.put("ht", params);

					ApiClient.http_post(Setting.getShareAlbumUrl(), map, null,
							this, REQUEST_APPLY_HOT_PHOTO, true);
				}
			}
		}
	}

//	private void requestApplyHotPhoto() {
//		if (mInstance == null) {
//			return;
//		}
//
//		// 申请热门相册
//		if (mIsApplyHotPhoto) {
//
//			String albumName = UserConfig.getConfigString(
//					MainTabActivity.getInstance(), Const.CONFIG_APP_ALBUM_NAME,
//					Const.DEFAULT_CUSTOM_ALBUM_NAME);
//			String albumApplyDesc = UserConfig.getConfigString(
//					MainTabActivity.getInstance(),
//					Const.CONFIG_APP_ALBUM_APPLY_DESC, "");
//
//			ArrayList<PhotoItem> dataList = PhotoItem.getPhotosByDate(
//					mLoginInfo.UserID, mCurrentDateString);
//			String result = "";
//			if (dataList != null && dataList.size() > 0) {
//				StringBuilder sb = new StringBuilder();
//				for (int i = 0; i < dataList.size(); i++) {
//					sb.append(dataList.get(i).pictureId);
//					sb.append("|");
//				}
//				sb.deleteCharAt(sb.length() - 1);
//
//				result = sb.toString();
//
//				Map<String, Object> map = new HashMap<String, Object>();
//				JSONObject params = new JSONObject();
//				try {
//					params.put("DeviceID", Setting.DEVICEID);
//					params.put("ApplicationID", Setting.APPLICATIONID);
//
//					params.put("UserID", mLoginInfo.UserID);
//					params.put("LoginToken", mLoginInfo.LoginToken);
//
//					params.put("AlbumDescription", albumApplyDesc);
//					params.put("PhotoIDs", result);//
//					params.put("AlbumName", albumName);
//					params.put("AlbumDate", mCurrentDateString);// new add
//				} catch (Exception e) {
//					e.printStackTrace();
//				}
//				map.put("ht", params);
//
//				ApiClient.http_post(Setting.getShareAlbumUrl(), map, null,
//						this, REQUEST_APPLY_HOT_PHOTO, false);
//			}
//		}
//	}

	@SuppressLint("HandlerLeak")
	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case MSG_APPLY_PHOTO_SUCCESS:

				UIHelper.showToast(MyApplication.getInstance(), "申请热门相册成功");

				UserConfig.setConfig(MyApplication.getInstance(),
						mCurrentDateString, true);
				
				destroy();
				break;
			case MSG_APPLY_PHOTO_FAIL:

				UIHelper.showToast(MyApplication.getInstance(), "申请热门相册失败");
				
				destroy();

				break;
			case MSG_UPLOAD_IMAGE_ERROR:

				UIHelper.showToast(MyApplication.getInstance(),
						"上传图片失败，请检查网络，重新上传..");
				
				destroy();
				break;

			default:
				break;
			}
		};
	};

	@Override
	public void RequestComplete(Object object, Object data) {

		if (object.equals(REQUEST_UPLOAD_IMAGE)) {
			boolean flag = false;
			try {
				JSONObject jsonObject = new JSONObject((String) data);
				JSONObject obj1 = (JSONObject) jsonObject.get("Result");
				JSONObject obj2 = (JSONObject) obj1.get("DetailInfo");

				int PhotoID = obj2.optInt("PhotoID");// 服务器返回需要保存的id
				// int NativePhotoID = obj2.optInt("NativePhotoID");//
				// 本地数据库唯一id对应
				// String PhotoUrl = obj2.optString("PhotoUrl");

				flag = PhotoItem.updatePhotoItemSyncById(mLoginInfo.UserID,
						mCurrentItemId, PhotoID);

			} catch (JSONException e) {
				e.printStackTrace();
			}

			LogUtilBase.LogD(null, String.format(
					"RequestComplete 第%d张图片上传结果==%s", mCurrentIndex,
					String.valueOf(flag)));

			mCurrentIndex++;
			uploadImageContent();
		} else if (object.equals(REQUEST_APPLY_HOT_PHOTO)) {

			boolean flag = false;
			try {
				JSONObject jsonObject = new JSONObject((String) data);
				JSONObject obj1 = (JSONObject) jsonObject.get("Result");
				JSONObject obj2 = (JSONObject) obj1.get("DetailInfo");

				int HotAlbumID = obj2.optInt("HotAlbumID");// 服务器返回需要保存的id
				LogUtilBase.LogD(null,
						"HotAlbumID==" + String.valueOf(HotAlbumID));
				flag = true;

			} catch (JSONException e) {
				e.printStackTrace();
			}

			mHandler.sendEmptyMessage(MSG_APPLY_PHOTO_SUCCESS);

			LogUtilBase.LogD(null, "REQUEST_APPLY_HOT_PHOTO==" + flag);
		}
	}

	@Override
	public void RequestError(Object object, int errorId, String errorMessage) {
		if (object.equals(REQUEST_UPLOAD_IMAGE)) {
			LogUtilBase.LogD(null, "上传图片失败    " + mCurrentIndex);

			// mCurrentIndex ++;
			// uploadImageContent();

			mHandler.sendEmptyMessage(MSG_UPLOAD_IMAGE_ERROR);
		} else if (object.equals(REQUEST_APPLY_HOT_PHOTO)) {

			mHandler.sendEmptyMessage(MSG_APPLY_PHOTO_FAIL);
			LogUtilBase.LogD(null, "REQUEST_APPLY_HOT_PHOTO==error");
		}

	}

}